package com.zyc.config;

import com.zyc.registry.zk.CuratorUtils;
import com.zyc.utils.threadpool.RpcThreadPoolFactoryUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * @author zyc
 * @create 2022--05--25 11:19
 */
@Slf4j
public class CustomShutdownHook {
    private static final CustomShutdownHook CUSTOM_SHUTDOWN_HOOK = new CustomShutdownHook();

    public static CustomShutdownHook getCustomShutdownHook() {
        return CUSTOM_SHUTDOWN_HOOK;
    }

    public void clearAll(int port) {
        log.info("调用clearAll钩子方法");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                log.info("进入clearAll钩子方法");
                InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), port);
                CuratorUtils.clearRegistry(CuratorUtils.getZkClient(), inetSocketAddress);
            } catch (UnknownHostException ignored) {
                log.info("clearAll钩子方法失败");
            }
            RpcThreadPoolFactoryUtil.shutDownAllThreadPool();
        }));
    }
}
